//
//  XLGSendQueuePool.m
//  etionCBLogic
//
//  Created by wjxfhxy on 15/10/28.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "XLGSendQueuePool.h"

@implementation XLGSendQueuePoolItem (XLGSendQueuePoolItemInternal)

-(void)setDelegate:(id<XLGSendQueuePoolItemDelegate>)delegate
{
    [self setAssociatedAssingValue:delegate withKey:"delegate"];
}

-(id<XLGSendQueuePoolItemDelegate>)delegate
{
    return [self associatedValueForKey:"delegate"];
}

- (BOOL)startItem
{
    return NO;
}

- (void)stopItem
{
    [self.delegate removeSendOperation:self];
}

@end

@interface XLGSendQueuePool ()
{
    NSLock *_lock;
    NSMutableArray *_pool;
    NSUInteger _maxCount;
}
@end

@implementation XLGSendQueuePool

@synthesize maxCount = _maxCount;

- (id)init
{
    self = [super init];
    
    _lock = [NSLock new];
    
    _pool = [NSMutableArray new];
    
    _maxCount = 1;
    
    return self;
}

- (void)dealloc
{
    [_lock release_mm];
    [_pool release_mm];
    superdealloc_mm;
}

- (BOOL)addSendOperation:(XLGSendQueuePoolItem*)sendQueuePoolItem
{
    __block BOOL b = NO;
    
    [_lock lock:^
    {
        if(_pool.count >= _maxCount)
        {
            b = NO;
        }
        else
        {
            b = YES;
            
            sendQueuePoolItem.delegate = self;
            
            [_pool addObject:sendQueuePoolItem];
        }
    }];
    
    if(b == YES)
    {
        b = [sendQueuePoolItem startItem];
        if(b != YES)
        {
            [sendQueuePoolItem stopItem];
        }
    }
    
    return b;
}

- (void)removeSendOperation:(XLGSendQueuePoolItem *)sendQueuePoolItem
{
    sendQueuePoolItem.delegate = nil;
    
    [_lock lock:^
    {
         [_pool removeObject:sendQueuePoolItem];
    }];
}

- (NSUInteger)currentCount
{
    __block NSUInteger count = 0;
    [_lock lock:^
    {
        count = _pool.count;
    }];
    return count;
}

-(NSArray*)items
{
    __block NSArray *itmes = nil;
    [_lock lock:^
    {
        itmes = [_pool copy];
    }];
    return itmes;
}

@end
